package org.adorsys.aderp.aderplogin.client;

import org.adorsys.aderp.aderplogin.client.common.Oauth2User;
import org.adorsys.aderp.aderplogin.client.common.Oauth2UserProvider;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.util.Assert;

/**
 * This bean is in charge of populating the user detail object with 
 * credentials required to run this app. 
 * 
 * In particular the user name that is required by the application for 
 * login.
 * 
 * It will contact the login application that maps oauth token to
 * a user permission profile and return that permission profile in form of a user detail.
 * 
 * @author francis
 *
 * @param <T>
 */
public class OauthTokenUserDetailsServiceWrapper implements
		AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken>, InitializingBean {

    private Oauth2UserProvider oauth2UserProvider;

    @Override
	public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.oauth2UserProvider, "Oauth2UserProvider must be set");
	}

	@Override
	public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token)
			throws UsernameNotFoundException {
		Object principal = token.getPrincipal();
		OAuth2AccessToken oAuth2AccessToken = (OAuth2AccessToken) principal;
		Oauth2User oauth2User = oauth2UserProvider.getUser(oAuth2AccessToken.getValue());
		return UserDetailsHelper.createUserDetails(oauth2User, null);		
	}

	public void setOauth2UserProvider(Oauth2UserProvider oauth2UserProvider) {
		this.oauth2UserProvider = oauth2UserProvider;
	}

}
